package com.realbrand.net.realbrandpay.ui.activity.wallet.personer;

import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.Toolbar;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.realbrand.net.realbrandpay.R;
import com.realbrand.net.realbrandpay.api.HTTPAPI;
import com.realbrand.net.realbrandpay.base.BaseActivity;
import com.realbrand.net.realbrandpay.inter.ICheckShelvesOpen;
import com.realbrand.net.realbrandpay.inter.IGetQrCode;
import com.realbrand.net.realbrandpay.ui.activity.wallet.order.OrderActivity;
import com.realbrand.net.realbrandpay.untils.Constant;
import com.realbrand.net.realbrandpay.untils.HttpRequest;
import com.realbrand.net.realbrandpay.untils.Static;
import com.realbrand.net.realbrandpay.zxing.util.L;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by Administrator on 2018/6/20.
 */

public class OpenScanActivity extends BaseActivity {
    @BindView(R.id.openScan_toolbar)
    Toolbar openScanToolbar;
    @BindView(R.id.openScan_iv_scan)
    ImageView openScanIvScan;

    String account;
    private boolean isStart=false;
    Thread thread;
    AlertDialog dialog;
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    //监测开关门
                    checkDoor();
                    break;
            }
        }


    };
    @BindView(R.id.openScan_iv_refresh)
    TextView openScanIvRefresh;

    private void checkDoor() {
        JSONObject object = new JSONObject();
        try {
            object.put("ScavengingUser", account);
            object.put("SOURCE", "OpenScanActivity");
            object.put("CREDENTIALS", "0");
            object.put("TERMINAL", "1");
            object.put("INDEX", Static.getDay());
            object.put("METHOD", "CheckShelvesOpen");
            RequestBody body = RequestBody.create(HTTPAPI.JSON, object.toString());
            ICheckShelvesOpen iCheckShelvesOpen = HttpRequest.request_BASE_URL_VERSION(ICheckShelvesOpen.class, HTTPAPI.BASE_TEXTURL);
            iCheckShelvesOpen.checkDoor(body).enqueue(new Callback<ResponseBody>() {
                @Override
                public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                    try {
                        String result = response.body().string();
                        L.d("货柜开门结果" + result);
                        JSONObject resultObject = new JSONObject(result);
                        String bOpen = resultObject.getString("bOpen");
                        if ("true".equals(bOpen)) {//开门成功
                            showDia(bOpen);
                        } else if ("false".equals(bOpen)) {//开门失败
                            showDia(bOpen);
                        } else if ("wait".equals(bOpen)) {
                            thread = new Thread(new Runnable() {
                                @Override
                                public void run() {
                                    SystemClock.sleep(3000);
                                    if (!isStart) {
                                        Message obtain = Message.obtain();
                                        obtain.what = 1;
                                        handler.sendMessage(obtain);
                                    }
                                }
                            });
                            thread.start();
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void onFailure(Call<ResponseBody> call, Throwable t) {

                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

    private void showDia(String bOpen) {
        LayoutInflater inflater = LayoutInflater.from(this);
        View view = inflater.inflate(R.layout.dialog_checkdoor, null);
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        dialog = builder.create();
        dialog.setView(view);
        Window window = dialog.getWindow();
        window.setGravity(Gravity.CENTER);
        TextView openText = (TextView) view.findViewById(R.id.dialog_checkDoor_open);
        TextView text = (TextView) view.findViewById(R.id.dialog_checkDoor_text);
        TextView clickText = (TextView) view.findViewById(R.id.dialog_checkDoor_click);
        if ("true".equals(bOpen)) {
            clickText.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    startActivity(new Intent(OpenScanActivity.this, OrderActivity.class));
                    OpenScanActivity.this.finish();
                    dialog.dismiss();
                }
            });
        } else if ("false".equals(bOpen)) {
            openText.setText("开柜失败");
            text.setText("请稍后再试");
            text.setTextColor(getResources().getColor(R.color.toolbar));
            text.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dialog.dismiss();
                    OpenScanActivity.this.finish();

                }
            });
            clickText.setVisibility(View.GONE);
        }
        dialog.show();
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(getLayoutId());
        ButterKnife.bind(this);
        openScanToolbar.setTitle("");
        openScanToolbar.setNavigationIcon(R.mipmap.ic_back);
        setSupportActionBar(openScanToolbar);
        openScanToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        SharedPreferences sharedPreferences = getSharedPreferences(Constant.shareName, MODE_PRIVATE);
        account = sharedPreferences.getString("account", "");
        //请求得到code
        getScanCode(account);
        setOnClick();
    }

    private void getScanCode(String account) {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("UserAccount", account);
            jsonObject.put("SOURCE", "OpenScanActivity");
            jsonObject.put("CREDENTIALS", "0");
            jsonObject.put("TERMINAL", "1");
            jsonObject.put("INDEX", Static.getDay());
            jsonObject.put("METHOD", "GetQrCode");
            RequestBody body = RequestBody.create(HTTPAPI.JSON, jsonObject.toString());
            IGetQrCode iGetQrCode = HttpRequest.request_BASE_URL(IGetQrCode.class);
            Call<ResponseBody> code = iGetQrCode.getCode(body);
            code.enqueue(new Callback<ResponseBody>() {
                @Override
                public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                    try {
                        String string = response.body().string();
                        L.d("获取二维码结果" + string);
                        JSONObject resultJson = new JSONObject(string);
                        String qrCode = resultJson.getString("qrCode");
                        Bitmap qrCodeBitmap = generateBitmap(qrCode, 560, 560);
                        openScanIvScan.setImageBitmap(qrCodeBitmap);
                        Message obtain = Message.obtain();
                        obtain.what = 1;
                        handler.sendMessage(obtain);
                    } catch (Exception e) {
                        e.printStackTrace();
                        L.d("获取二维码异常" + e.toString());
                    }
                }

                @Override
                public void onFailure(Call<ResponseBody> call, Throwable t) {

                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    protected int getLayoutId() {
        return R.layout.act_openscan;
    }

    @Override
    protected void setOnClick() {
        openScanIvRefresh.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.openScan_iv_refresh:
                getScanCode(account);
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        isStart=true;
    }

    /**
     * 生成二维码
     *
     * @param content
     * @param width
     * @param height
     * @return
     */
    private Bitmap generateBitmap(String content, int width, int height) {
        QRCodeWriter qrCodeWriter = new QRCodeWriter();
        Map<EncodeHintType, String> hints = new HashMap<>();
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
        try {
            BitMatrix encode = qrCodeWriter.encode(content, BarcodeFormat.QR_CODE, width, height, hints);
            int[] pixels = new int[width * height];
            for (int i = 0; i < height; i++) {
                for (int j = 0; j < width; j++) {
                    if (encode.get(j, i)) {
                        pixels[i * width + j] = 0x00000000;
                    } else {
                        pixels[i * width + j] = 0xffffffff;
                    }
                }
            }
            return Bitmap.createBitmap(pixels, 0, width, width, height, Bitmap.Config.RGB_565);
        } catch (WriterException e) {
            e.printStackTrace();
        }
        return null;
    }

}
